<template>
  <div>
    <el-upload
      :file-list="fileList"
      action="#"
      list-type="picture-card"
      :http-request="httpRequest"
      :on-remove="onremove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :class="{disable:fileList.length ===1}"
    >
      <i class="el-icon-plus " />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDuhIiy0p493pOo0znPo4A3jRIn8IJDAFH',
  SecretKey: 'KVgopmpjRwQnCA0e5Zt59AB3xwmqleXR'
})
export default {
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    onChange(file, filelist) {
      this.fileList = filelist
    },
    onremove(file, filelist) {
      this.fileList = filelist
    },
    httpRequest(option) {
      cos.putObject({
        // 配置
        Bucket: 'hr81-1314424513', // 存储桶名称
        Region: 'ap-guangzhou', // 存储桶地域
        Key: option.file.name, // 文件名作为key
        // StorageClass: 'STANDARD', // 此类写死
        Body: option.file // 将本地的文件赋值给腾讯云配置
        // // 进度条
        // onProgress: (params) => {
        //   this.percent = params.percent * 100
        // }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          console.log('腾讯云上传成功', data)
          // 修改图片状态
          this.fileList[0].status = 'success'
          // 修改图片地址
          this.fileList[0].url = 'https://' + data.Location
        }
      })
    },
    beforeUpload(file) {
      const max = 1024 * 1024
      if (file.size > max) {
        this.$message.error('图片过大')
        return false
      }

      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('仅支持上传jpg/png格式图片')
        return false
      }
    }

  }
}
</script>
<style lang="scss" scoped>
//上传组件样式
.disable{
::v-deep  .el-upload--picture-card{
  display: none;
}
}

</style>
